<?php
require_once 'library/config.php';

function __autoload($class_name) {
    include_once 'library/' . strtolower($class_name) . '.php';
}

$user = new User();
if ($user->isLogged()) {
    $registerOrLoginNeeded = false;
} else {
    $registerOrLoginNeeded = true;

    $facebook = new Facebook(array(
                'appId' => FB_ID,
                'secret' => FB_SECRET,
            ));

    $fbUser = $facebook->getUser();

    if ($fbUser) {
        try {

            $userProfile = $facebook->api('/me');
            if ($user->fbLogin($fbUser)) {
                $registerOrLoginNeeded = false;
            } else {
                $db = Db::init();

                $sth = $db->prepare("SELECT * FROM users WHERE email = ?");
                $sth->execute(array($userProfile['email']));

                if (false != $sth->fetch()) {
                    $sth = $db->prepare("UPDATE users SET facebook = ? WHERE email = ?");
                    if ($sth->execute(array($fbUser, $userProfile['email']))) {
                        if ($user->fbLogin($fbUser))
                            $registerOrLoginNeeded = false;
                    }
                }
            }
        } catch (FacebookApiException $e) {
            $fbUser = null;
        }
    }
}
?>
<!DOCTYPE html>

<html lang="en-US">
    <head>
        <title>Simple Registration System</title>
        <style>
            body { font: normal 14px Verdana; }
            h1 { font-size: 24px; }
            h2 { font-size: 18px; }
        </style>
    </head>
    <body>

        <div id="wrap">

            <section id="main">

                <?php if (false === $registerOrLoginNeeded): ?>

                    <h1>Welcome</h1>
                    <p>You may now enjoy the site.</p>

                <?php else: ?>

                    <div id="fb-root"></div>
                    <script type="text/javascript">
                        window.fbAsyncInit = function() {
                            FB.init({
                                appId      : '<?php echo $facebook->getAppID() ?>', // App ID
                                channelUrl : 'http://soevar.com/channel.html', // Channel File
                                status     : true, // check login status
                                cookie     : true, // enable cookies to allow the server to access the session
                                oauth      : true, // enable OAuth 2.0
                                xfbml      : true  // parse XFBML
                            });
                            FB.Event.subscribe('auth.login', function(response) {
                                window.location.reload();
                            });
                            FB.Event.subscribe('auth.logout', function(response) {
                                window.location.reload();
                            });
                        };
                        (function(d){
                            var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
                            js = d.createElement('script'); js.id = id; js.async = true;
                            js.src = "//connect.facebook.net/en_US/all.js";
                            d.getElementsByTagName('head')[0].appendChild(js);
                        }(document));
                    </script>

                    <h1>Registration or login needed</h1>

                    <div style="float: left; margin-right: 15px;">

                        <h2>Register</h2>
                        <p>You need to register to fully enjoy this site.</p>

                        <div class="fb-registration"
                             data-fields='[{"name":"name"},
                             {"name":"birthday"},
                             {"name":"location"},
                             {"name":"gender"},
                             {"name":"email"},
                             {"name":"username","description":"Username","type":"text"},
                             {"name":"password"}]'
                             data-redirect-uri="http://soevar.com:8085/login/fb/register.php"
                             width="300">
                        </div>

                    </div>

                    <div style="float: left;">

                        <h2>Login</h1>
                            <p>
                                If you already have an account you can login
                                using the form below:
                            </p>
                            <form action="login.php" method="POST">
                                <div>
                                    <label for="username">Username:</label>
                                    <input type="text" id="username" name="username" />
                                </div>
                                <div>
                                    <label for="password">Password:</label>
                                    <input type="password" id="password" name="password" />
                                </div>
                                <div><input type="submit" value="Login" /></div>
                            </form>

                    </div>
                    <div style="clear:both;"> </div>

                <?php endif; ?>

            </section>

        </div>
        <p>
            If you previously registered for this site using Facebook,
            you can now login using your Facebook account.
        </p>
        <div class="fb-login-button" data-show-faces="false" scope="email"></div>
    </body>
</html>
